<template>
  <div class="salesperson-list">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="销售员姓名">
            <el-input v-model="searchForm.name" placeholder="请输入销售员姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select v-model="searchForm.department" placeholder="请选择部门">
              <el-option label="全部" value=""></el-option>
              <el-option label="电子产品部" value="electronics"></el-option>
              <el-option label="服装部" value="clothing"></el-option>
              <el-option label="食品部" value="food"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="在职" value="active"></el-option>
              <el-option label="离职" value="inactive"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增销售员</el-button>
        <el-button type="success" @click="handleExport">导出数据</el-button>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="salespersonList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号码" width="120"></el-table-column>
        <el-table-column prop="department" label="所属部门" width="120">
          <template slot-scope="scope">
            {{ getDepartmentText(scope.row.department) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="monthlyTarget" label="月度目标" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.monthlyTarget.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="monthlyAchieved" label="月度业绩" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.monthlyAchieved.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerCount" label="客户数量" width="100"></el-table-column>
        <el-table-column prop="joinDate" label="入职日期" width="180"></el-table-column>
        <el-table-column label="操作" fixed="right" width="320">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="success" @click="handleTarget(scope.row)">设置目标</el-button>
            <el-button size="mini" type="primary" @click="handleCustomers(scope.row)">客户</el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 'active' ? 'danger' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '离职' : '复职' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="salespersonForm" :rules="rules" ref="salespersonForm" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="salespersonForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="salespersonForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-select v-model="salespersonForm.department" placeholder="请选择部门">
            <el-option label="电子产品部" value="electronics"></el-option>
            <el-option label="服装部" value="clothing"></el-option>
            <el-option label="食品部" value="food"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职日期" prop="joinDate">
          <el-date-picker
            v-model="salespersonForm.joinDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="基本工资" prop="baseSalary">
          <el-input-number 
            v-model="salespersonForm.baseSalary" 
            :min="0"
            :precision="2"
            :step="100"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="提成比例" prop="commission">
          <el-input-number 
            v-model="salespersonForm.commission" 
            :min="0"
            :max="100"
            :precision="2"
          >
            <template slot="append">%</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="salespersonForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 设置目标对话框 -->
    <el-dialog title="设置销售目标" :visible.sync="targetDialogVisible" width="40%">
      <el-form :model="targetForm" :rules="targetRules" ref="targetForm" label-width="100px">
        <el-form-item label="目标月份" prop="month">
          <el-date-picker
            v-model="targetForm.month"
            type="month"
            placeholder="选择月份"
            value-format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售目标" prop="target">
          <el-input-number 
            v-model="targetForm.target" 
            :min="0"
            :precision="2"
            :step="1000"
            style="width: 200px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="targetForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="targetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTarget">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSalespeopleList,
  createSalesperson,
  updateSalesperson,
  setSalesTarget,
  updateSalespersonStatus,
  exportSalespeopleData
} from '@/api/salespeople'
import { saveAs } from 'file-saver'

export default {
  name: 'SalespersonList',
  data() {
    // 手机号码验证
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      // 搜索表单
      searchForm: {
        name: '',
        phone: '',
        department: '',
        status: ''
      },
      // 表格数据
      salespersonList: [
        {
          id: 1,
          name: '李四',
          phone: '13800138001',
          department: 'electronics',
          status: 'active',
          monthlyTarget: 100000,
          monthlyAchieved: 80000,
          customerCount: 50,
          joinDate: '2023-01-01',
          baseSalary: 5000,
          commission: 5,
          remark: '优秀销售员'
        }
      ],
      loading: false,
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 100,

      // 新增/编辑对话框
      dialogVisible: false,
      dialogTitle: '新增销售员',
      salespersonForm: {
        name: '',
        phone: '',
        department: '',
        joinDate: '',
        baseSalary: 0,
        commission: 0,
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        joinDate: [
          { required: true, message: '请选择入职日期', trigger: 'change' }
        ],
        baseSalary: [
          { required: true, message: '请输入基本工资', trigger: 'blur' }
        ],
        commission: [
          { required: true, message: '请输入提成比例', trigger: 'blur' }
        ]
      },

      // 目标设置对话框
      targetDialogVisible: false,
      targetForm: {
        month: '',
        target: 0,
        remark: ''
      },
      targetRules: {
        month: [
          { required: true, message: '请选择目标月份', trigger: 'change' }
        ],
        target: [
          { required: true, message: '请输入销售目标', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取部门文本
    getDepartmentText(department) {
      const departmentMap = {
        electronics: '电子产品部',
        clothing: '服装部',
        food: '食品部'
      }
      return departmentMap[department] || department
    },
    // 获取数据
    async fetchData() {
      try {
        this.loading = true
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        const res = await getSalespeopleList(params)
        this.salespersonList = res.data.items
        this.total = res.data.total
      } catch (error) {
        console.error('获取销售员列表失败：', error)
        this.$message.error('获取销售员列表失败')
      } finally {
        this.loading = false
      }
    },
    // 搜索方法
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        name: '',
        phone: '',
        department: '',
        status: ''
      }
    },
    // 新增销售员
    handleAdd() {
      this.dialogTitle = '新增销售员'
      this.salespersonForm = {
        name: '',
        phone: '',
        department: '',
        joinDate: '',
        baseSalary: 0,
        commission: 0,
        remark: ''
      }
      this.dialogVisible = true
    },
    // 编辑销售员
    handleEdit(row) {
      this.dialogTitle = '编辑销售员'
      this.salespersonForm = { ...row }
      this.dialogVisible = true
    },
    // 提交表单
    async handleSubmit() {
      this.$refs.salespersonForm.validate(async valid => {
        if (valid) {
          try {
            const isEdit = !!this.salespersonForm.id
            const apiMethod = isEdit ? updateSalesperson : createSalesperson
            const data = { ...this.salespersonForm }
            
            if (isEdit) {
              await apiMethod(data.id, data)
            } else {
              await apiMethod(data)
            }
            
            this.$message.success(`${isEdit ? '编辑' : '新增'}成功`)
            this.dialogVisible = false
            this.fetchData()
          } catch (error) {
            console.error('保存失败：', error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    // 设置目标
    handleTarget(row) {
      this.currentSalesperson = row
      const now = new Date()
      this.targetForm = {
        month: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`,
        target: row.monthlyTarget,
        remark: ''
      }
      this.targetDialogVisible = true
    },
    // 提交目标设置
    async submitTarget() {
      this.$refs.targetForm.validate(async valid => {
        if (valid) {
          try {
            await setSalesTarget(this.currentSalesperson.id, this.targetForm)
            this.$message.success('目标设置成功')
            this.targetDialogVisible = false
            this.fetchData()
          } catch (error) {
            console.error('目标设置失败：', error)
            this.$message.error('目标设置失败')
          }
        }
      })
    },
    // 查看客户
    handleCustomers(row) {
      // TODO: 跳转到该销售员的客户列表
      this.$router.push(`/customers/list?salespersonId=${row.id}`)
    },
    // 切换状态
    async handleToggleStatus(row) {
      const action = row.status === 'active' ? '离职' : '复职'
      try {
        await this.$confirm(`确认将该销售员设置为${action}状态?`, '提示', {
          type: 'warning'
        })
        
        const newStatus = row.status === 'active' ? 'inactive' : 'active'
        await updateSalespersonStatus(row.id, newStatus)
        
        this.$message.success(`${action}操作成功`)
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('状态更新失败：', error)
          this.$message.error('状态更新失败')
        }
      }
    },
    // 导出数据
    async handleExport() {
      try {
        const params = { ...this.searchForm }
        const res = await exportSalespeopleData(params)
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        saveAs(blob, `销售员数据_${new Date().toLocaleDateString()}.xlsx`)
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败：', error)
        this.$message.error('导出失败')
      }
    },
    // 分页方法
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    }
  }
}
</script>

<style lang="scss" scoped>
.salesperson-list {
  .search-bar {
    margin-bottom: 20px;
  }

  .toolbar {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 